/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package actions;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import models.DAO.UserDAO;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import models.beans.User;

/**
 *
 * @author Hoang Dong Tien
 */
public class login extends org.apache.struts.action.Action {
    
    /* forward name="success" path="" */
    private static final String ADMIN = "ADMIN";
    private static final String EMPLOYEE = "EMPLOYEE";
    private static final String DENIED = "DENIED";
    
    /**
     * This is the action called from the Struts framework.
     * @param mapping The ActionMapping used to select this instance.
     * @param form The optional ActionForm bean for this request.
     * @param request The HTTP Request we are processing.
     * @param response The HTTP Response we are processing.
     * @throws java.lang.Exception
     * @return
     */
    @Override
    public ActionForward execute(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        User loginform = (User)form;
        User user = UserDAO.getOneUserForLogin(loginform.getUsername(), loginform.getPassword());

        if(user == null){
            request.setAttribute("error", "Username and Password are not correct.");
            return mapping.findForward(login.DENIED);
        }else{
            request.getSession().setAttribute("user", user);
            System.out.println("Role : " + user.getRole());
            if(user.getRole().equals(User.ROLE_ADMIN)){
                response.sendRedirect("admin/dashboard.jsp");
                return mapping.findForward(login.ADMIN);
            }else if(user.getRole().equals(User.ROLE_EMPLOYEE)){
                response.sendRedirect("employee/EventComing.do");
                //System.out.println("employee/EventComing.do");
                return mapping.findForward(login.EMPLOYEE);
            }else{
                request.setAttribute("error", "Unknown Permission.");
                return mapping.findForward(login.DENIED);
            }
        }

    }
}
